﻿using NLog;
using EpubFactory.Common;
using EpubFactory.Zhuishu.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace EpubFactory.Zhuishu.Service
{
    public class HttpHelper
    {
        protected static readonly Logger _log = LogManager.GetLogger("http", typeof(HttpHelper));
        public const string USER_AGENT = "YouShaQi/2.25.2 (iPhone; iOS 9.3.2; Scale/2.00)";
        public static string GET(string url, params KeyValuePair<string, string>[] args)
        {
            string param = string.Empty;
            if (args.Length > 0)
            {
                param = "?" + string.Join("&", args.Select(g => string.Format("{0}={1}", g.Key, g.Value)));
            }
            string requestUrl = url + param;
            var request = WebRequest.CreateHttp(requestUrl);
            request.Method = "GET";
            request.ProtocolVersion = new Version(1, 1);
            request.UserAgent = USER_AGENT;
            //request.Headers.Add("X-Device-Id", "631cf212b409f949264fad9ba1ba1daa");
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var repStream = response.GetResponseStream())
                {
                    using (var reader = new StreamReader(repStream))
                    {
                        var result = reader.ReadToEnd();
                        _log.Debug("GET {0} {1}", requestUrl, response.StatusCode);
                        return result;
                    }
                }
            }
        }
        public static T Get<T>(string url, params KeyValuePair<string, string>[] args)
        {
            string result = GET(url, args);
            return JsonHelper.Deserialize<T>(result);
        }
    }
    public class QueryResult
    {
        public bool ok { get; set; }
    }
    public class FuzzySearchResult : QueryResult
    {
        public List<QueryBookInfo> books { get; set; }
    }
    public class MixTocResult : QueryResult
    {
        public MixTocInfo mixToc { get; set; }
    }
    public class ChapterInfoResult : QueryResult
    {
        public ChapterInfo chapter { get; set; }
    }
    public class AutoComplateResult : QueryResult
    {
        public List<string> keywords { get; set; }
    }
}
